package com.evan.wj.controller;

import com.evan.wj.pojo.Book;
import com.evan.wj.pojo.Node;
import com.evan.wj.pojo.User;
import com.evan.wj.pojo.ViewNode;
import com.evan.wj.result.Result;
import com.evan.wj.result.ResultFactory;
import com.evan.wj.service.NodeService;
import com.evan.wj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class NodeContraller {
    @Autowired
    private NodeService nodeService;

    @Autowired
    private UserService userService;


    public List<ViewNode> list(){
        return nodeService.list();
    }

    @PostMapping("/api/node")
    public Result personalNode(@RequestBody User user){
        System.out.println(user);

        if (null == user.getUsername() || "".equals(user.getUsername())){
            return ResultFactory.buildFailResult("用户为空，非法行为");
        }
        User byName = userService.getByName(user.getUsername());
        if (null == byName){
            return ResultFactory.buildFailResult("非法行为");
        }

        List<ViewNode> viewNodes = nodeService.myNode(byName.getId());

        return ResultFactory.buildSuccessResult(viewNodes);

    }

    @PostMapping("/api/node/save")
    public Result save(@RequestBody Node node){
        System.out.println(node);
        Node save = nodeService.save(node);
        return ResultFactory.buildSuccessResult(save);
    }

    @CrossOrigin
    @PostMapping("/api/node/{cid}/categories")
    public Result searchResult(@PathVariable("cid") int cid,@RequestBody User user) {
        System.out.println("------------------");
        System.out.println(user);

        if (0 == cid) {
            return personalNode(user);
        } else {
            User byName = userService.getByName(user.getUsername());
            List<ViewNode> viewNodes = nodeService.myNode(byName.getId(), cid);
            return ResultFactory.buildSuccessResult(viewNodes);
        }
    }
    @PostMapping("/api/node/delete")
    public Result delete(@RequestBody Node node){
        nodeService.delete(node.getId());
        return ResultFactory.buildSuccessResult(null);
    }

}
